<?php

// +----------------------------------------------------------------------
// | MC PHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author kobe [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------


namespace app\api\controller\v1;

use app\api\controller\Base;
use AppendIterator;
use think\facade\Db;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode as EndroidQrCode;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use app\common\service\ApiReturn;

/**
 * 二维码接口
 */
class Qrcode extends Base
{
    /**
     * 获取邀请二维码
     * @param  array  $data [description]
     * @param  array  $user [description]
     * @return [type]       [description]
     */
    public function invitationQRcode($data=[],$user=[])
    {
        $invite_code = $user['invite_code'];
        $domain = sysconfig('site','site_domain');
        $content = $domain . '/share?mobile='.$user['mobile'].'&invite_code=' . $invite_code;
        $url = ROOT_PATH . 'public/storage/qrcode/' . $invite_code . '.png';//存框架的位置
        $code_url = $domain . '/storage/qrcode/' . $invite_code . '.png';//二维码的访问地址
        $writer = new PngWriter();
        $qrCode = EndroidQrCode::create($content)//跳转的url地址
                ->setEncoding(new Encoding('UTF-8'))//设置编码格式
                ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())//设置纠错级别为低
                ->setSize(300)//大小
                ->setMargin(10)//边距
                ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())//设置圆轮大小边距
                ->setForegroundColor(new Color(0, 0, 0))//前景色
                ->setBackgroundColor(new Color(255, 255, 255)); //背景色

        if(!file_exists('storage/qrcode')){
            mkdir('storage/qrcode',0755,true);
        }
        $result = $writer->write($qrCode);
        header('Content-Type: '.$result->getMimeType());
        $result->getString();
     
        $result->saveToFile($url);

        return ApiReturn::r(1,compact('invite_code','code_url'),'请求成功');
    }

    /**
     * 获取小程序二维码
     * @param  array  $data [description]
     * @param  array  $user [description]
     * @return [type]       [description]
     */
    public function getMiniQrcode($data=[],$user=[])
    {
        $invite_code = $user['invite_code'];
        $scene = "invite_code=$invite_code";
        $url = 'pages/tabBar/home/home';      
        //要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。  
        $apptype = $data['env_version'] ?? 'release';
        $env_version = "release";
        $check_path = true;
        if($apptype == "trial"){
            $env_version = "trial";
            $check_path = false;
        }
        if($apptype == "develop"){
            $env_version = "develop";
            $check_path = false;
        }            
        $result = addons_action('WeChat', 'AuthCode', 'getUnlimitedQRCode', [
            $scene, $url, 430, true, ["r" => "0", "g" => "0", "b" => "0"],true,null, $env_version,$check_path
        ]);
        $code_url = "data:image/png;base64," . $result;
        return ApiReturn::r(1,compact('code_url'),'请求成功');
    }

    /**
     * 获取带参公众号二维码
     * @param  array  $data [description]
     * @param  array  $user [description]
     * @return [type]       [description]
     */
    public function getTicketQrcode($data=[],$user=[])
    {
        $name = '北京十方泰和自主健康生活圈';
        $url = \think\facade\Cache::get('ticketQrcode');
        if ($url) {
            return ApiReturn::r(1, compact('url','name'), '请求成功');
        }
        try {
            $encode = addons_action('WeChat', 'AuthCode', 'createTicketQrcode', ['mini']);
            $decode = json_decode($encode, true);
            $ticket = urlencode($decode['ticket']);
            $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket;
            \think\facade\Cache::set('ticketQrcode', $url);
        } catch (\Exception $e) {
            return ApiReturn::r(0, null, '请求失败'.$e->getMessage());
        }
        return ApiReturn::r(1, compact('url', 'name'), '请求成功');
    }
}
